<template>
  <div class="app-container">
    <!-- 搜索栏 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.keyword"
        placeholder="搜索用户名、手机号、邮箱"
        style="width: 200px;"
        class="filter-item"
        @keyup.enter.native="handleFilter"
      />
      <el-select
        v-model="listQuery.userType"
        placeholder="用户类型"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option label="求职者" value="1" />
        <el-option label="招聘者" value="2" />
      </el-select>
      <el-select
        v-model="listQuery.status"
        placeholder="状态"
        clearable
        style="width: 120px"
        class="filter-item"
      >
        <el-option label="正常" value="1" />
        <el-option label="禁用" value="0" />
      </el-select>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >
        搜索
      </el-button>
      <el-button
        class="filter-item"
        type="primary"
        icon="el-icon-plus"
        @click="handleCreate"
      >
        新增用户
      </el-button>
      <el-button
        :loading="downloadLoading"
        class="filter-item"
        type="primary"
        icon="el-icon-download"
        @click="handleDownload"
      >
        导出
      </el-button>
    </div>

    <!-- 表格 -->
    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column
        label="ID"
        prop="id"
        sortable="custom"
        align="center"
        width="80"
      />
      <el-table-column label="头像" align="center" width="80">
        <template slot-scope="{row}">
          <el-avatar :src="row.avatar" size="40">
            <img src="/default-avatar.png" />
          </el-avatar>
        </template>
      </el-table-column>
      <el-table-column label="用户名" prop="username" align="center" width="120" />
      <el-table-column label="姓名" prop="realName" align="center" width="100" />
      <el-table-column label="手机号" prop="phone" align="center" width="120" />
      <el-table-column label="邮箱" prop="email" align="center" min-width="150" />
      <el-table-column label="用户类型" align="center" width="100">
        <template slot-scope="{row}">
          <el-tag :type="row.userType === 1 ? 'primary' : 'success'">
            {{ row.userType === 1 ? '求职者' : '招聘者' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" width="80">
        <template slot-scope="{row}">
          <el-tag :type="row.status === 1 ? 'success' : 'danger'">
            {{ row.status === 1 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="注册时间" align="center" width="160">
        <template slot-scope="{row}">
          {{ row.createTime | parseTime }}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button type="primary" size="mini" @click="handleUpdate(row)">
            编辑
          </el-button>
          <el-button
            v-if="row.status === 1"
            size="mini"
            type="warning"
            @click="handleModifyStatus(row, 0)"
          >
            禁用
          </el-button>
          <el-button
            v-else
            size="mini"
            type="success"
            @click="handleModifyStatus(row, 1)"
          >
            启用
          </el-button>
          <el-button size="mini" type="danger" @click="handleDelete(row)">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 用户对话框 -->
    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :rules="rules"
        :model="temp"
        label-position="left"
        label-width="80px"
        style="width: 400px; margin-left:50px;"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="temp.username" :disabled="dialogStatus === 'update'" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="dialogStatus === 'create'">
          <el-input v-model="temp.password" type="password" />
        </el-form-item>
        <el-form-item label="姓名" prop="realName">
          <el-input v-model="temp.realName" />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="temp.phone" />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="temp.email" />
        </el-form-item>
        <el-form-item label="用户类型" prop="userType">
          <el-select v-model="temp.userType" placeholder="请选择">
            <el-option label="求职者" value="1" />
            <el-option label="招聘者" value="2" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus === 'create' ? createData() : updateData()">
          确定
        </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import Pagination from '@/components/Pagination'

export default {
  name: 'UserList',
  components: { Pagination },
  filters: {
    parseTime(time) {
      if (!time) return ''
      return new Date(time).toLocaleString()
    }
  },
  data() {
    return {
      tableKey: 0,
      list: [],
      total: 0,
      listLoading: true,
      downloadLoading: false,
      listQuery: {
        page: 1,
        limit: 20,
        keyword: undefined,
        userType: undefined,
        status: undefined,
        sort: '+id'
      },
      temp: {
        id: undefined,
        username: '',
        password: '',
        realName: '',
        phone: '',
        email: '',
        userType: '1'
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑用户',
        create: '新增用户'
      },
      rules: {
        username: [{ required: true, message: '用户名不能为空', trigger: 'blur' }],
        password: [{ required: true, message: '密码不能为空', trigger: 'blur' }],
        realName: [{ required: true, message: '姓名不能为空', trigger: 'blur' }],
        phone: [
          { required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '邮箱不能为空', trigger: 'blur' },
          { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      // TODO: 调用用户列表API
      setTimeout(() => {
        this.list = [
          {
            id: 1,
            username: 'zhangsan',
            realName: '张三',
            phone: '13800138001',
            email: 'zhangsan@example.com',
            userType: 1,
            status: 1,
            avatar: '/default-avatar.png',
            createTime: new Date()
          },
          {
            id: 2,
            username: 'lisi',
            realName: '李四',
            phone: '13800138002',
            email: 'lisi@example.com',
            userType: 2,
            status: 1,
            avatar: '/default-avatar.png',
            createTime: new Date()
          }
        ]
        this.total = 2
        this.listLoading = false
      }, 1000)
    },
    
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    
    handleModifyStatus(row, status) {
      this.$confirm(`确定要${status === 1 ? '启用' : '禁用'}该用户吗?`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        row.status = status
        this.$message({
          type: 'success',
          message: `${status === 1 ? '启用' : '禁用'}成功!`
        })
      })
    },
    
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },
    
    resetTemp() {
      this.temp = {
        id: undefined,
        username: '',
        password: '',
        realName: '',
        phone: '',
        email: '',
        userType: '1'
      }
    },
    
    handleCreate() {
      this.resetTemp()
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    createData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          // TODO: 调用创建用户API
          this.list.unshift(Object.assign({}, this.temp, { id: Date.now() }))
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '创建用户成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    
    handleUpdate(row) {
      this.temp = Object.assign({}, row)
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    
    updateData() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          const tempData = Object.assign({}, this.temp)
          // TODO: 调用更新用户API
          const index = this.list.findIndex(v => v.id === this.temp.id)
          this.list.splice(index, 1, tempData)
          this.dialogFormVisible = false
          this.$notify({
            title: '成功',
            message: '更新用户成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },
    
    handleDelete(row) {
      this.$confirm('确定要删除该用户吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // TODO: 调用删除用户API
        const index = this.list.findIndex(v => v.id === row.id)
        this.list.splice(index, 1)
        this.$notify({
          title: '成功',
          message: '删除用户成功',
          type: 'success',
          duration: 2000
        })
      })
    },
    
    handleDownload() {
      this.downloadLoading = true
      // TODO: 调用导出用户API
      setTimeout(() => {
        this.downloadLoading = false
        this.$message({
          message: '导出成功',
          type: 'success'
        })
      }, 1000)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .filter-container {
    padding: 20px;
    background: white;
    border-radius: 4px;
    margin-bottom: 20px;
    
    .filter-item {
      margin-right: 10px;
    }
  }
}
</style>